﻿using Mapster;
using Raffles.OA.Data;
using Raffles.OA.Service;
using Raffles.OA.Utility;
using SqlSugar;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Raffles.OA.WebApp.Controllers
{
    public class LoginController : Controller
    {
        public static SqlSugarScope _dbContext = ReportDB.Db;
        private BaseItemService _baseItemService;
        public LoginController()
        {
            _baseItemService = new BaseItemService();
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Index2()
        {
            return View();
        }

        /// <summary>
        /// 系统登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<ActionResult> CheckLogin(string account, string password)
        {
            Stopwatch sw = new Stopwatch();
            try
            {
                sw.Reset();
                sw.Start();
                var entity = _dbContext.Queryable<User>()
                                       .Includes(x => x.Roles)
                                       .First(x => x.Account.ToLower().Equals(account.Trim().ToLower()));
                if (entity == null)
                {
                    throw new Exception("用户不存在");
                }
                else if (entity.DeletedMark)
                {
                    throw new Exception("用户已删除");
                }
                else if (!entity.EnabledMark)
                {
                    throw new Exception("用户已禁用");
                }
                else if (!CommonHelper.CreatePassword(password.Trim(), entity.Salt).Equals(entity.Password))
                {
                    throw new Exception("用户密码错误");
                }
                else
                { 

                    OperatorModel operatorModel = new OperatorModel()
                    {
                        Id = entity.Id,
                        Account = entity.Account,
                        RealName = entity.RealName,
                        DepartmentId = entity.DepartmentId,
                        DataScope = entity.Roles.Count() == 0 ? (int)DataScopeEnum.ALL : entity.Roles.FirstOrDefault().DataScope,
                        IsSystem = entity.IsSystem,
                        Color = entity.Color.IsEmpty() ? "bg-black" : entity.Color,
                        OperateRate = entity.OperateRate,
                        RoleCode=entity.RoleCode
                    };
                    OperatorProvider.Provider.AddCurrent(operatorModel);
                    sw.Stop();

                    Log log = new Log()
                    {
                        LogType = (int)DbLogType.Login,
                        ClassName = $"/{this.GetType().Name}",
                        MethodName = $"/{MethodBase.GetCurrentMethod().Name}",
                        Parameter = "{\"username\":" + account + ",\"password\":" + password + "}",
                        Description = $"{NetHelper.Browser}-{NetHelper.GetOSVersion()}",
                        ExecuteTime = sw.ElapsedMilliseconds.ToInt(),
                        ExecuteResult = (int)OperateStatusEnum.Success,//执行状态
                        ExecuteResultData = entity.ToJson(),
                        ExecuteExceptionLog = "登录成功",//执行结果日志
                        OperateAccount = entity.Account,
                        OperateRealName = entity.RealName,
                        OperateIPAddress = Net.Ip,
                        CreatedOn = DateTime.Now
                    };
                    await _dbContext.Insertable<Log>(log).ExecuteCommandAsync();
                    await _baseItemService.LoadQuotationRelatePriceCache();
                    await _baseItemService.LoadQuotationDestinationCache();
                    return Json(DataResult<string>.Success("/Home/Index", "登录成功"), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                sw.Stop();
                Log log = new Log()
                {
                    LogType = (int)DbLogType.Login,
                    ClassName = $"/{this.GetType().Name}",
                    MethodName = $"/{MethodBase.GetCurrentMethod().Name}",
                    Parameter = "{\"username\":" + account + ",\"password\":" + password + "}",
                    Description = $"{NetHelper.Browser}-{NetHelper.GetOSVersion()}",
                    ExecuteTime = sw.ElapsedMilliseconds.ToInt(),
                    ExecuteResult = (int)OperateStatusEnum.Fail,
                    ExecuteExceptionLog = "登录失败,错误原因:" + ex.Message,
                    OperateIPAddress = Net.Ip,
                    CreatedOn = DateTime.Now
                };
                await _dbContext.Insertable<Log>(log).ExecuteCommandAsync();
                return Json(DataResult.Error($"{ex.Message}"), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult ChangePassword()
        {
            User entity = _dbContext.Queryable<User>().InSingle(OperatorProvider.Provider.GetCurrent().Id);
            return View(entity);
        }

        [HttpPost]
        public ActionResult ChangePasswordJson(PasswordDto passwordDto)
        {
            User user = _dbContext.Queryable<User>().InSingle(OperatorProvider.Provider.GetCurrent().Id);
            if (!CommonHelper.CreatePassword(passwordDto.OldPassword, user.Salt).Equals(user.Password))
            {
                return Json(DataResult.Error($"旧密码输入不正确！"));
            }
            user.Password = CommonHelper.CreatePassword(passwordDto.NewPassword, user.Salt);
            user.UpdatedOn = DateTime.Now;
            user.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
            _dbContext.Updateable<User>(user).ExecuteCommand();
            return Json(DataResult.Success($"密码修改成功！"));
        }

        public ActionResult Logout()
        {
            OperatorModel operatorModel = OperatorProvider.Provider.GetCurrent();
            CacheHelper.RemoveCache($"{operatorModel.Account}_{operatorModel.Id}");
            OperatorProvider.Provider.RemoveCurrent();
            //移除资源中心缓存
            _baseItemService.RemoveQuotationRelatePriceCache();
            _baseItemService.RemoveQuotationDestinationCache();
            return RedirectToAction("Index");
        } 
    }
}